from HTMLParser import HTMLParser
from mimetools import choose_boundary
from urllib import urlencode
from urllib2 import Request
try:
	import json
except ImportError:
	import simplejson as json

def GetJsonData(s):
	while True:
		try:
			return json.loads(s)
		except json.JSONDecodeError, e:
			if e.msg != "Invalid \\escape" or  s[e.pos:e.pos + 2] != "\\'":
				raise
			s = s[:e.pos] + "'" + s[e.pos + 2:]

class FirstFormTargetExtractor(HTMLParser):
	def handle_starttag(self, tag, attrs):
		if not hasattr(self, 'target') and tag == "form":
			for name, value in attrs:
				if name == 'action':
					self.target = value

def GetFirstFormTarget(htmldata):
	parser = FirstFormTargetExtractor()
	parser.feed(htmldata)
	parser.close
	return parser.target

DEFAULT_HEADER = {
	"Connection": "keep-alive",
	"User-Agent": "Mozilla/5.0",
}
USE_FORMDATA = False

ENCODE_TEMPLATE= """--%(boundary)s
Content-Disposition: form-data; name="%(name)s"

%(value)s
""".replace('\n','\r\n')
def encode_multipart_formdata(fields):
	"""
	fields is a sequence of (name, value) elements for regular form fields.
	Return (content_type, body) ready for httplib.HTTP instance
	"""
	boundary = choose_boundary()
	body = ""
	for key, value in fields.iteritems():
		body += ENCODE_TEMPLATE % {
					'boundary': boundary,
					'name': str(key),
					'value': str(value)
				}
	body += '--%s--\n\r' % boundary
	content_type = 'multipart/form-data; boundary=%s' % boundary
	return body, content_type

def MakeDataRequest(url, params, headers = DEFAULT_HEADER, use_formdata = USE_FORMDATA):
	if use_formdata:
		body, content_type = encode_multipart_formdata(params)
		request = Request(url, body, headers)
		request.add_header("Content-Type", content_type)
	else:
		request = Request(url, urlencode(params), headers)
	return request



__ALL__ = ['GetFirstFormTarget', 'GetJsonData', 'MakeDataRequest', 'DEFAULT_HEADER']
